<template>
	<!-- 设备巡检  定检和巡检 使用同一个 主表 INSPCETYPE 1是定检，0是巡检 详情 -->
	<view class="">
		<!-- 主表信息 -->
		<view class="mian-table">
			<view class="main-table-title">
				<view class="mian-table-name">
					设备信息
				</view>
			</view>
			<view class="mian-table-content">
				<formItem :formConfig='filterMainCF' :formVal='formValueMain' @searchBaseP='searchBaseP'>
					<template #ExTextSearch=" {config} ">
						<view class="ExTextSearch-wrap">
							<textarea v-model="formValueMain[config.ID]" row="3" class="ExTextSearch"
								placeholder="请输入或选择"></textarea>
							<view class="btn-2">
								<button type="warn" size="mini"
									@click="saveCY(formValueMain[config.ID], formValueMain.PK_REMARK)">
									{{ formValueMain.PK_REMARK ?'取消':'收藏' }}
								</button>

								<picker @change=" (e)=> bindPickerChange(e,'Main')" :value="index" :range="CYarray"
									range-key="MSG">
									<button type="primary" size="mini" @click="openCY(index)">常用</button>
								</picker>
							</view>
						</view>
					</template>
					<template #ExEnumRadio=" {config} ">
						<radio-group @change=" (val)=> radioChange(val,'Main')">
							<label class="radio">
								<radio value="1" :checked="formValueMain[config.ID] ==1  " />维修
							</label>
							<label class="radio">
								<radio value="2" :checked="formValueMain[config.ID] ==2  " />更换
							</label>
							<label class="radio">
								<radio value="3" :checked="formValueMain[config.ID] ==3  " />正常
							</label>
						</radio-group>
					</template>

				</formItem>
			</view>
		</view>
		<!-- 子表信息 -->
		<view class="sub-table">
			<view class="sub-table-title">
				<view class="sub-table-title-name">物资信息 </view>
				<view class="sub-table-title-contrl" v-if="bstype == 0">
					<text class="dicon diconjia-xianxingfangkuang" @click="addMater"></text>
					<!-- <text class="dicon diconsaomiao" @click="ScanEvent"></text> -->
				</view>

				<view class="" v-else>
					<button :type="seeType==1  ? 'primary':'' " size="mini" class="mr-10"
						@click="SetSeeType(1)">巡检周期</button>
					<button :type="seeType==2  ? 'primary':'' " size="mini" @click="SetSeeType(2)"
						v-if="userInfo.authModel.includes('G201')">查看成本</button>
				</view>

			</view>

			<template v-if="seeType==0">
				<view class="sub-table-content" v-for="(item,index) in formValueSub " :key="index"
					@click="activeSub(index)">
					<formItem :formConfig="filterSubCF" :formVal="item" :formIndex="index" @searchBaseP='searchBaseP'>
						<template #ExTextSearch=" {config} ">
							<view class="ExTextSearch-wrap">
								<textarea v-model="item[config.ID]" row="3" class="ExTextSearch"
									placeholder="请输入或选择"></textarea>
								<view class="btn-2">
									<button type="warn" size="mini" @click="saveCY(item[config.ID], item.PK_REMARK)">
										{{ item.PK_REMARK ?'取消':'收藏' }}
									</button>

									<picker @change="(e)=> bindPickerChange(e, index)" :value="index" :range="CYarray"
										range-key="MSG">
										<button type="primary" size="mini" @click="openCY(index)">常用</button>
									</picker>
								</view>
							</view>
						</template>
						<template #ExEnumRadio=" {config} ">
							<radio-group @change=" (val)=> radioChange(val,index)">
								<label class="radio">
									<radio value="1" :checked="item[config.ID] ==1  " />维修
								</label>
								<label class="radio">
									<radio value="2" :checked="item[config.ID] ==2  " />更换
								</label>
								<label class="radio">
									<radio value="3" :checked="item[config.ID] ==3  " />正常
								</label>
							</radio-group>
						</template>

					</formItem>
				</view>
			</template>

			<template v-else>
				<view class="sub-table-content my-flex" v-for="(item,index) in formValueSub " :key="index">
					<view class="title">
						<view class="name">
							{{ item.MATERIALNAME }}
						</view>
						<view class="time" v-if="seeType==1">
							请于{{ item.VBDEF1 }}前完成
						</view>
						<view class="time" v-else-if="seeType==2">
							数量：{{ item.NUM  }} {{ item.UNIT }}
						</view>
					</view>
					<view class="date" v-if="seeType==1">
						每{{ item.VBDEF2 }}天1次
					</view>

					<view class="money" v-if="seeType==2">
						成本：{{ item.VBDEF5 }}
					</view>

				</view>
			</template>

		</view>

		<view class="operation">
			<button class="operation-button border-right" @click="finishSubmit"
				:disabled=" seeType==0? isDisabled :false ">
				{{ seeType==0?'提交':'返回' }}
			</button>
		</view>

	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import config from '@/common/config.js'
	import formItem from '@/components/form/form_item.vue'
	import api from '@/common/api.js'
	const plug = uni.requireNativePlugin('Html5app-Gprinter');
	let _self, valueSub, activeType, activeID, activeSubIndex, ResultData = {};
	let t = {
		ware: 1,
		org: 3,
		company: 2
	};
	export default {
		data() {
			return {
				config: [],
				bstype: "",
				mainType: '',
				subType: '',
				formValueMain: '',
				formValueSub: [],
				SBData: {},
				seeType: 0,
				isDisabled: false,
				CYarray: [],
				myActiveSub: 0,

			}
		},
		computed: {
			...mapState(['userInfo', 'checkData']),
			filterMainCF() {
				var t = this.config.App[this.mainType].filter(item => {
					return item.IsShow == 1;
				})
				return t;
			},
			filterSubCF() {
				return this.config.App[this.subType].filter(item => {
					return item.IsShow == 1;
				})
			}
		},
		components: {
			formItem
		},
		onLoad(p) {
			_self = this
			// this.setCheckData([])
			this.config = config
			this.listenOnce()
			this.bstype = p.type
			this.$utils.setPageTitle(p.title)
			if (this.bstype == 1) {
				this.mainType = 'patrolMan'
				this.subType = 'patrolSub'
				this.formValueMain = this.checkData[0]
				this.formValueMain.account = getApp().globalData.Account
				this.bstype == 1 ? this.getDetail() : null

				console.log('this.formValueMain', this.formValueMain);
			} else {
				this.mainType = 'patrolMan2'
				this.subType = 'patrolSub2'
				this.SBData.SBID = p.SBID
				this.SBData.SBName = p.SBName
			}

			this.initConifg(p.type)


		},

		methods: {
			...mapMutations(["setCheckData"]),
			// 初始化配置数据
			initConifg(bsType) {
				if (this.bstype == 1) {
					this.formValueMain = this.checkData[0]
				} else {
					let valueMain = this.initForm(this.config.App.patrolMan2),
						valueSub = this.initForm(this.config.App.patrolSub2);
					this.formValueMain = valueMain
					this.formValueSub.push(valueSub)

					this.formValueMain.PK_GROUP = this.userInfo.PK_GROUP
					this.formValueMain.GROUPNAME = this.userInfo.GROUPNAME
					this.formValueMain.PK_ORG = this.userInfo.ORGANIZEID
					this.formValueMain.ORGNAME = this.userInfo.ORGNAME

					this.formValueMain.PK_EQUIP = this.SBData.SBID
					this.formValueMain.EQUIPNAME = this.SBData.SBName
				}
				this.formValueMain.account = getApp().globalData.Account
			},
			// 激活的第几个子表
			activeSub(i) {
				activeSubIndex = i;
			},

			SetSeeType(t) {
				this.seeType = t
			},

			radioChange(e, index) {
				let v = e.detail.value
				if (index == 'Main') {
					this.formValueMain.INSPECTSTATUS = v
					this.formValueSub.forEach(i => {
						i.BILLSTATUS = v
					})
					console.log('radioChange', v, this.formValueSub[0]);
				} else {
					this.formValueSub[index].BILLSTATUS = v
				}

			},

			initForm(config) {
				let valueMain = {};
				config.forEach(item => {
					try {
						if (item.Other && item.Controls == "ExEnum") {
							let m = JSON.parse(item.Other);
							valueMain[item.ID + 'Range'] = Array.isArray(m) ? m : []
							valueMain[item.ID + 'Index'] = 0
						}
					} catch (e) {
						console.error(e);
					}
					valueMain[item.ID] = item.Default == '0' ? 0 : (valueMain[item.Default] || '')
				})
				return valueMain;
			},

			openCY(i) {
				this.myActiveSub = i
				activeSubIndex = i
				this.axios({
					url: '/API/APPCommon/GetEQMSGINFO',
					data: {},
					isLoading: 1
				}).then(res => {
					let {
						Result
					} = res;
					this.CYarray = Result
				})
			},

			saveCY(val, PK_REMARK) {
				if (!val) {
					return this.$utils.tips('请先输入巡检说明')
				}
				let URL = '/API/APPCommon/SaveEQMSG',
					data = {
						MSG: val
					};
				if (PK_REMARK) {
					URL = '/API/APPCommon/DelEQMSG'
					data = {
						BILLNO: PK_REMARK
					}
				}
				this.axios({
					url: URL,
					data: data,
					isLoading: 1
				}).then(res => {
					let {
						Result,
						Message
					} = res;
					this.$utils.tips(Message)
					if (PK_REMARK) {
						this.formValueSub[activeSubIndex].PK_REMARK = ''
					}
					this.CYarray = Result
				})
			},

			bindPickerChange(e, type) {
				let v = e.detail.value;
				if (type == 'Main') {
					this.formValueMain.VMEMO = this.CYarray[v].MSG
					this.formValueMain.PK_REMARK = this.CYarray[v].BILLNO
				} else {
					this.formValueSub[activeSubIndex].PK_REMARK = this.CYarray[v].BILLNO
					// this.$forceUpdate()
					let newItem = this.formValueSub[activeSubIndex];
					newItem.REMARK = this.CYarray[v].MSG
					this.$set(this.formValueSub, activeSubIndex, newItem)
				}
				// this.$set( this.formValueSub , activeSubIndex, {PK_REMARK: this.CYarray[v].BILLNO})
				// console.log(123,this.CYarray[v].BILLNO , this.formValueSub[activeSubIndex] );
			},

			// 基础数据查询
			searchBaseP(tnt) {
				// console.log('searchBaseP', tnt );
				activeType = tnt.type
				activeID = tnt.id
				activeSubIndex = tnt.subIndex
				this.listenOnce()
				let queryParames = "",
					search_PK_GROUP = '';
				let URL = "/pages/public/search?t=" + activeType + "&queryjson=" + queryParames + '&PK_GROUP=' +
					search_PK_GROUP
				uni.navigateTo({
					url: URL
				});
			},


			// 初始监听
			listenOnce() {
				uni.$off('getSelectItem')
				uni.$once("getSelectItem", function(data) {
					console.log(888, activeType, activeSubIndex);
					switch (activeType) {
						case "EQBOM": // 设备
							_self.formValueMain.EQUIPNAME = data.VNAME;
							_self.formValueMain.PK_EQUIP = data.BILLNO;
							break;
						case "BA_MATER": // 物资
							_self.formValueSub[activeSubIndex].MATERIALNAME = data.MATERIALNAME;
							_self.formValueSub[activeSubIndex].MATSPEC = data.MATSPEC;
							_self.formValueSub[activeSubIndex].PK_MATERIAL = data.BILLNO;
							break;
						default:
							break;
					}
				});
			},

			// 添加物资
			addMater() {
				let AddItem = {
					PK_EQUIP: '',
					EQUIPNAME: '',
					IMPUNUM: ''
				}
				this.formValueSub.push(AddItem)
			},

			getDetail() {
				let URL = '/API/APPCommon/GetRegularInspectionDetails',
					queryDetail = {
						keyValue: this.formValueMain.BILLNO
					};
				console.log(77, queryDetail);
				this.axios({
					url: URL,
					data: queryDetail,
					isLoading: 1
				}).then(res => {
					let {
						Result
					} = res;
					let valueSub = this.initForm(this.config.App.patrolSub);

					let copySub = Result.Details.map(i => {
						let copy = JSON.parse(JSON.stringify(valueSub))
						i = Object.assign(copy, i)
						return i
					})
					this.formValueSub = copySub
					// console.log(valueSub);
					// console.log(this.formValueSub);
				}).catch(err => {
					console.log(err);
				})
			},

			// 扫描设备
			ScanEvent() {

				this.$utils.openScanUtils(0, 0, (res) => {
					if (res.includes('TYPE:8')) {
						let arr = res.split('|');
						let AddItem = {
							PK_EQUIP: '',
							EQUIPNAME: '',
							IMPUNUM: ''
						}
						let hasSB = this.formValueSub.filter(i => {
							return i.PK_EQUIP == arr[2]
						})
						if (!hasSB.length) {
							AddItem.EQUIPNAME = arr[1]
							AddItem.PK_EQUIP = arr[2]
							if (!_self.formValueSub[_self.formValueSub.length - 1].PK_EQUIP) {
								_self.formValueSub[_self.formValueSub.length - 1].EQUIPNAME = arr[1]
								_self.formValueSub[_self.formValueSub.length - 1].PK_EQUIP = arr[2]
							} else {
								_self.formValueSub.push(AddItem)
							}
						}
					} else {
						this.$utils.tips('非设备二维码,无法使用')
					}
				})
			},

			finishSubmit() {
				if (this.seeType > 0) {
					this.seeType = 0
					return;
				}
				this.isDisabled = true
				let newSub = this.formValueSub.map(item => {
					let newItem = {
						..._self.formValueMain,
						...item,
						IMPUATIONOR: _self.userInfo.Account
					}
					return newItem
				})

				let savedata = {
					...this.formValueMain,
					"DETAILS": this.formValueSub // JSON.stringify(this.formValueSub),
				}
				if (!this.formValueMain.PK_EQUIP) {
					this.isDisabled = false
					return _self.$utils.tips('请选择设备')
				} else if (!this.formValueSub[0].PK_MATERIAL) {
					this.isDisabled = false
					return _self.$utils.tips('请选择物资')
				}

				let URL = '/API/APPCommon/SaveRegularInspection'
				// console.log(URL);
				this.axios({
					url: URL,
					data: savedata,
					isLoading: 1
				}).then(res => {
					_self.$utils.tips('提交成功')
					setTimeout(a => {
						uni.$emit('refresh', {
							refresh: true
						});
						uni.navigateBack({})
						this.isDisabled = false
					}, 1500)
				}).catch(err => {
					this.isDisabled = false
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		padding-bottom: 110rpx;
	}

	.mr-10 {
		margin-right: 20rpx;
	}

	.mian-table {
		background-color: #ffffff;
		color: #555555;

		.main-table-title {
			margin-top: 20rpx;
			padding: 30rpx 24rpx;
			border-bottom: 1rpx solid #f1f1f1;

			.mian-table-name {
				font-weight: 800;
				font-size: 32rpx;
				position: relative;
				padding-left: 40rpx;
			}

			.mian-table-name:before {
				content: "";
				width: 10rpx;
				height: 32rpx;
				line-height: 32rpx;
				position: absolute;
				margin: 0 16rpx;
				border-radius: 10rpx;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				background-color: #1677ff;
			}
		}

		.mian-table-content {
			padding: 0 30rpx;
		}
	}

	.sub-table {
		color: #555555;

		.sub-table-title {
			background-color: #ffffff;
			display: flex;
			margin-top: 20rpx;
			padding: 30rpx 24rpx;
			border-bottom: 1rpx solid #f1f1f1;
			justify-content: space-between;
			align-items: center;

			.sub-table-title-name {
				font-weight: 800;
				font-size: 32rpx;
				position: relative;
				padding-left: 40rpx;
			}

			.sub-table-title-name:before {
				content: "";
				width: 10rpx;
				height: 32rpx;
				line-height: 32rpx;
				position: absolute;
				margin: 0 16rpx;
				border-radius: 10rpx;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				background-color: #1677ff;
			}

			.dicon {
				font-size: 50rpx;
				margin: 0 10rpx;
			}
		}

		.sub-table-content {
			margin-top: 20rpx;
			background-color: #ffffff;
			padding: 0 30rpx;

			.title {
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee;
				width: 100%;

				.name {
					font-weight: 600;
					color: #333;
					margin-bottom: 10rpx;
				}

			}

			.date {
				background-color: #f1f1f1;
				width: 250rpx;
				padding: 20rpx;
				border-radius: 10rpx;
				text-align: center;
			}

			.money {
				width: 200rpx;
			}
		}
	}

	.my-flex {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}



	.ExTextSearch-wrap {
		display: flex;
		width: 100%;
		justify-content: space-between;

		.btn-2 {
			width: 100rpx;
			height: 60rpx;
			position: relative;
			top: 0rpx;

			button {
				width: 100rpx;
				height: 60rpx;
				padding: 0;
				margin-right: 10rpx;
			}
		}

		.ExTextSearch {
			height: 120rpx;
			width: 380rpx;
		}
	}
</style>